package com.byxy.xyqas.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import com.byxy.xyqas.dao.ForumDao;
import com.byxy.xyqas.dao.TabDao;
import com.byxy.xyqas.dao.TipDao;
import com.byxy.xyqas.dao.UserDao;
import com.byxy.xyqas.entity.Forum;
import com.byxy.xyqas.entity.Tab;
import com.byxy.xyqas.entity.Tip;
import com.byxy.xyqas.entity.User;
import com.byxy.xyqas.service.TipService;
import com.byxy.xyqas.vo.TipVO;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * TipServiceImpl
 */
@Service
@Transactional
public class TipServiceImpl implements TipService {
    @Autowired
    private TipDao tipDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TabDao tabDao;

    @Autowired
    private ForumDao forumDao;

    @Override
    public List<TipVO> findAll() {
        List<Tip> tips = tipDao.findAll();
        List<TipVO> tipvos = new ArrayList<>();
        for (Tip tip : tips) {
            TipVO vo = new TipVO();
            BeanUtils.copyProperties(tip, vo);
            User u = userDao.getOne(tip.getUserId());
            if (u.getUserNick() != null && u.getUserNick().equals(""))
                vo.setUserName(u.getUserNick());
            else
                vo.setUserName(u.getUserName());
            Tab t = tabDao.getOne(tip.getTabId());
            vo.setTabName(t.getTabName());
            Forum f = forumDao.getOne(t.getForumId());
            vo.setForumName(f.getForumName());
            tipvos.add(vo);
        }
        return tipvos;
    }

    @Override
    public TipVO get(Integer tipId) {
        Tip t = tipDao.getOne(tipId);
        TipVO vo = new TipVO();
        User u = userDao.getOne(t.getUserId());
        Tab tab = tabDao.getOne(t.getTabId());
        Forum f = forumDao.getOne(tab.getForumId());
        BeanUtils.copyProperties(t, vo);
        vo.setUserName(u.getUserName());
        vo.setUserNick(u.getUserNick());
        vo.setForumId(f.getForumId());
        return vo;
    }

    @Override
    public void add(TipVO tipVO) {
        Tip t = new Tip();
        BeanUtils.copyProperties(tipVO, t);
        tipDao.save(t);
    }

    @Override
    public void update(TipVO tipVO) {
        Tip t = new Tip();
        BeanUtils.copyProperties(tipVO, t);
        t.setTabId(tipVO.getTabId());
        tipDao.save(t);
    }

    @Override
    public void changeTipStatus(Integer tipIsDeleted, Integer tipIsKnot, Integer tipId) {
        Tip tip = tipDao.getOne(tipId);
        tip.setTipIsDeleted(tipIsDeleted);
        tip.setTipIsKnot(tipIsKnot);
        tipDao.save(tip);
        TipVO vo = new TipVO();
        BeanUtils.copyProperties(tip, vo);
    }

}